Completed
Push — master ( c8749b...21bf41 )
by Dongxin
32s
created

common.js ➔ isJSON   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 4
c 1
b 0
f 1
nc 5
nop 1
dl 0
loc 15
rs 9.2
1
// Copyright © 2017 Tangdongxin
2
3
// Permission is hereby granted, free of charge, to any person obtaining
4
// a copy of this software and associated documentation files (the "Software"),
5
// to deal in the Software without restriction, including without limitation
6
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7
// and/or sell copies of the Software, and to permit persons to whom the
8
// Software is furnished to do so, subject to the following conditions:
9
// The above copyright notice and this permission notice shall be included
10
// in all copies or substantial portions of the Software.
11
12
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
14
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
15
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
17
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
18
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
20
21
var bgColor; // background color
0 ignored issues
show
Unused Code introduced by
The variable bgColor seems to be never used. Consider removing it.
Loading history...
22
var intColor; // integer color
0 ignored issues
show
Unused Code introduced by
The variable intColor seems to be never used. Consider removing it.
Loading history...
23
var strColor; // string color
0 ignored issues
show
Unused Code introduced by
The variable strColor seems to be never used. Consider removing it.
Loading history...
24
var keyColor; // k-v key color
0 ignored issues
show
Unused Code introduced by
The variable keyColor seems to be never used. Consider removing it.
Loading history...
25
var defaultColor; // default text color
0 ignored issues
show
Unused Code introduced by
The variable defaultColor seems to be never used. Consider removing it.
Loading history...
26
var fontStyle; // font-family
0 ignored issues
show
Unused Code introduced by
The variable fontStyle seems to be never used. Consider removing it.
Loading history...
27
var fontSize; // font-size
0 ignored issues
show
Unused Code introduced by
The variable fontSize seems to be never used. Consider removing it.
Loading history...
28
var strictOnly; // only deal with the application/json response
0 ignored issues
show
Unused Code introduced by
The variable strictOnly seems to be never used. Consider removing it.
Loading history...
29
var hideDetails; // hide the count and size
30
var dontBeatify; // hide the [str] or [json]
0 ignored issues
show
Unused Code introduced by
The variable dontBeatify seems to be never used. Consider removing it.
Loading history...
31
32
// ===========================================
33
// DEFAULT VALUES
34
// ===========================================
35
var RAND = "MIKE";
36
var HOV  = "H" + RAND;
37
var DIV  = "D" + RAND;
38
var KEY  = "K" + RAND;
39
var STR  = "S" + RAND;
40
var BOOL = "B" + RAND;
41
var ERR  = "E" + RAND;
42
var COLL = "C" + RAND;
43
// fontStyle    = "Consolas";
44
// bgColor      = "#FDF6E3";
45
// intColor     = "#657A81";
46
// strColor     = "#2AA198";
47
// keyColor     = "#B58900";
48
// defaultColor = "#586E75";
49
// strictOnly   = false;
50
// hideDetails  = false;
51
// dontBeatify  = false;
52
53
// ===========================================
54
// COMMON FUNCTIONS
55
// ===========================================
56
function onError(result, error) {
0 ignored issues
show
Unused Code introduced by
The parameter error is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
57
    console.log(result);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
58
}
59
60
function reconvert(str) {
61
    str = str.replace(/(\\u)(\w{1,4})/gi, function($0) {
62
        return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{1,4})/g, "$2")), 16)));
63
    });
64
    str = str.replace(/(&#x)(\w{1,4});/gi, function($0) {
65
        return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{1,4})(%3B)/g, "$2"), 16));
66
    });
67
    str = str.replace(/(&#)(\d{1,6});/gi, function($0) {
68
        return String.fromCharCode(parseInt(escape($0).replace(/(%26%23)(\d{1,6})(%3B)/g, "$2")));
69
    });
70
71
    return str;
72
}
73
74
function units(size) {
75
    return size > 1048576 ? (0 | (size / 1048576)) + "MB" :
76
        size > 1024 ? (0 | (size / 1024)) + "KB" :
77
        size + "B";
78
}
79
80
function fragment(div, a, b) {
81
    var frag = document.createDocumentFragment();
82
    frag.appendChild(document.createTextNode(a));
83
    if (b) {
84
        frag.appendChild(div.cloneNode());
85
        frag.appendChild(document.createTextNode(b));
86
    } else {
87
        frag.appendChild(document.createElement("br"));
88
    }
89
    return frag;
90
}
91
92
function change(node, query, name, set) {
93
    var list = node.querySelectorAll(query),
94
        i = list.length;
95
    for (; i--;) list[i].classList[set ? "add" : "remove"](name);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
96
}
97
98
function draw(str, current, isEmbed=false) {
99
    var re = /("(?:((?:https?|file):\/\/(?:\\?\S)+?)|(?:\\?.)*?)")\s*(:?)|-?\d+\.?\d*(?:e[+-]?\d+)?|true|false|null|[[\]{},]|(\S[^-[\]{},"\d]*)/gi;
100
    var node = document.createElement("div");
101
    node.classList.add(DIV);
102
    var link = document.createElement("a");
103
    var span = document.createElement("span");
104
    var info = document.createElement("i");
105
    var colon = document.createTextNode(": ");
106
    var comma = fragment(node, ",");
107
    var path = [];
108
    var cache = {
109
        "{": fragment(node, "{", "}"),
110
        "[": fragment(node, "[", "]")
111
    };
112
113
    node.className = "R" + RAND;
114
    link.classList.add("L" + RAND);
115
    if (isEmbed) {
116
        info.classList.add("IJSON" + RAND);
117
    } else {
118
        info.classList.add("I" + RAND);
119
    }
120
121
    parse(str, re);
122
123
    current.innerHTML = node.innerHTML;
124
125
    function parse(str, re) {
126
        str = reconvert(str);
127
        var match, val, tmp, i = 0;
128
        var len = str.length;
129
        try {
130
            for (; match = re.exec(str);) {
131
                val = match[0];
132
                if (val == "{" || val == "[") {
133
                    path.push(node);
0 ignored issues
show
Bug introduced by
The variable node is changed as part of the for loop for example by node.lastChild.previousSibling on line 135. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
134
                    node.appendChild(cache[val].cloneNode(true));
135
                    node = node.lastChild.previousSibling;
136
                    node.len = 1;
137
                    node.start = re.lastIndex;
138
                } else if ((val == "}" || val == "]") && node.len) {
139
                    if (node.childNodes.length) {
140
                        tmp = info.cloneNode();
141
                        if (!hideDetails) {
142
                            tmp.dataset.content = node.len + (
143
                                node.len == 1 ?
144
                                (val == "]" ? " item, " : " property, ") :
145
                                (val == "]" ? " items, " : " properties, ")
146
                            ) + units(re.lastIndex - node.start + 1);
147
                        }
148
149
                        if ((val = node.previousElementSibling) && val.className == KEY) {
150
                            tmp.dataset.key = reconvert(val.textContent.slice(1, -1).replace(/'/, "\\'"));
151
                        }
152
                        node.parentNode.insertBefore(tmp, node);
153
                    } else {
154
                        node.parentNode.removeChild(node);
155
                    }
156
                    node = path.pop();
157
                } else if (val == ",") {
158
                    node.len += 1;
159
                    node.appendChild(comma.cloneNode(true));
160
                } else {
161
                    if (match[2]) {
162
                        tmp = link.cloneNode();
163
                        tmp.href = match[2].replace(/\\"/g, '"');
164
                    } else {
165
                        tmp = span.cloneNode();
166
                    }
167
                    tmp.textContent = match[1] || val;
168
                    tmp.classList.add(match[3] ? KEY : match[1] ? STR : match[4] ? ERR : BOOL);
169
                    node.appendChild(tmp);
170
                    if (match[3]) {
171
                        node.appendChild(colon.cloneNode());
172
                    }
173
                }
174
                if (++i > 1000) {
175
                    document.title = (0 | (100 * re.lastIndex / len)) + "% of " + units(len);
176
                    return setTimeout(function() {
177
                        parse(str, re)
178
                    });
179
                }
180
            }
181
            document.title = "";
182
            JSON.parse(str);
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
183
        } catch (e) {
184
            console.log(e);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
185
            alert(e);
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
186
            // TODO: find a better way to report error
187
            // tmp = document.createElement("h3");
188
            // tmp.className = ERR;
189
            // tmp.textContent = e;
190
            // box.insertBefore(tmp, box.firstChild);
191
        }
192
    }
193
}
194
195
function isJSON(str) {
196
    if (typeof str == 'string') {
197
        try {
198
            var obj = JSON.parse(str);
0 ignored issues
show
Unused Code introduced by
The variable obj seems to be never used. Consider removing it.
Loading history...
199
            if (str.indexOf('{') > -1) {
200
                return true;
201
            } else {
202
                return false;
203
            }
204
        } catch (e) {
205
            return false;
206
        }
207
    }
208
    return false;
209
}
210